<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-01 15:35:09
 * @LastEditTime: 2020-03-11 18:07:04
 * @LastEditors: Please set LastEditors
 -->
<!doctype html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport"
		content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0,viewport-fit=cover" />
	<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
	<title>Hello APP</title>
	<link rel="stylesheet" type="text/css" href="../css/vant.css">
	<link rel="stylesheet" type="text/css" href="../css/base.css" />
	<link rel="stylesheet" type="text/css" href="../css/local.css" />
	<script>
        if(!Object.assign){
            alert('您的手机安卓版本过低 请升级至6.0以上后重试!')
        }
        
    </script>
	<script type="text/javascript" src="../script/jquery.js"></script>
	<script type="text/javascript" src="../script/vue.min.js"></script>
	<script type="text/javascript" src="../script/vant.min.js"></script>
	<script type="text/javascript" src="../script/fastclick.js"></script>
	<script type="text/javascript" src="../script/base.js"></script>
	<script type="text/javascript" src="../script/db.js"></script>
	<script type="text/javascript" src="../script/jquery.signalR-2.4.1.min.js"></script>
	<script type="text/javascript" src="http://106.15.33.39:9981/signalr/hubs"></script>
	<script type="text/javascript" src="../script/signalr-mediate.js"></script>
	<script type="text/javascript" src="../script/moment.js"></script>
	<style type="text/css">
		body {
			background: #efefef;
		}

		.body-no-head {
			height: calc(100% - 50px);
			position: relative;
		}

		.van-info {
			border: 1px solid #ee0a24;
		}
	</style>
</head>

<body>
	<div id="app" v-cloak>
		<div class="init-full">
			<div class="body-no-head">

			</div>
			<van-tabbar inactive-color="#ffffff" active-color="#cd1b21" v-model="tabbarActive" @change="changeTabbar">
				<van-tabbar-item icon="home-o">主页</van-tabbar-item>
				<van-tabbar-item icon="search">查询</van-tabbar-item>
				<van-tabbar-item icon="apps-o">分类</van-tabbar-item>
				<van-tabbar-item icon="shopping-cart-o">购物车</van-tabbar-item>
				<van-tabbar-item icon="user-o">我的</van-tabbar-item>
			</van-tabbar>

		</div>
	</div>
</body>
<script type="text/javascript">
	var vm;
	apiready = function () {
		//$('.init-full').show();

		if(!window.localStorage.getItem('isRefresh')){
			window.localStorage.clear();
			window.localStorage.setItem('isRefresh','1')
		}


		if (api.connectionType == 'none') {
            api.alert({
                title: '福路德直购',
                msg: '无法连接到当前网络 请检查是否开启网络权限',
            }, function (ret, err) {

            });
        }

		var mine;
		var isOpenChatList = false;

		var friend = '';
		var groups = '';

		api.addEventListener({
			name: 'setUnRedMsg'
		}, function (ret, err) {
			vm.dot = ret.value.dot;
		});

		api.addEventListener({
			name: 'getUnReadMsgRepeat'
		}, function (ret, err) {
			FLD.ajax('getGroupList', {}, function (res) {
				groups = [];
				for (var i = 0; i < res.ds.length; i++) {
					groups.push({
						groupname: res.ds[i].GroupName,
						id: res.ds[i].GroupID.toString(),
						avatar: "../image/group.png" //群组头像
					})
				}
				vm.getUnReadMsg();
			})
		});



		api.addEventListener({
			name: 'openChatList'
		}, function (ret, err) {
			isOpenChatList = ret.value.isOpenChatList;
		});

		api.addEventListener({
			name: 'openChat'
		}, function (ret, err) {
			vm.openChat();
		});

		api.addEventListener({
			name: 'sendMineMsg'
		}, function (ret, err) {
			var msgObj = ret.value.msgObj;

			var sendmsg = function () {
				if (msgObj.type == 'friend') {
					$.signalrApi.server.chatMsg(mine.contextIDs, mine.id, msgObj.toUserID, msgObj.content);
				}
				else {
					$.signalrApi.server.groupMsg(mine.contextIDs, mine.id, msgObj.toUserID, msgObj.content);
				}
			}



			try {
				$.signalrApi.server.clientLive();
				sendmsg();
			} catch (e) {
				$.signalrApi.start(function () {
					var userInfo = FLD.getUserInfo();
					$.signalrApi.server.clientConnect(userInfo.UserID);
					setTimeout(function () {
						sendmsg();
					}, 500)
				});
			}


		});

		FLD.exitApp();
		window.localStorage.setItem('safeAreaTop', api.safeArea.top);
		window.localStorage.setItem('safeAreaBottom', api.safeArea.bottom);
		window.localStorage.setItem('systemType', api.systemType);


		// DB.initDatabase(function () {
		// 	DB.createTable(function () {
		// 		// alert('创建成功')
		// 	});
		// })


		var recMp3 = api.require('recMp3');
		var audioStreamer = api.require('audioStreamer');



		$.clientCallBacks = {};
		var signalRHelper = function () {
			$.signalrApi({
				serverUrl: "http://" + FLD.serverIP,
				clientHub: "IMHub",
				clientEvents: [
					{
						name: "onServiceClientConnect",
						method: function (data) {
							$.clientCallBacks["onServiceClientConnect"](data);
						}
					},
					{
						name: "onChatMsg",
						method: function (userId, msg, timestap) {
							$.clientCallBacks["onChatMsg"](userId, msg, timestap);
						}
					},
					{
						name: "onGroupMsg",
						method: function (userId, groupId, msg, timestap) {
							$.clientCallBacks["onGroupMsg"](userId, groupId, msg, timestap);
						}
					},
					{
						name: "onUserOnlineNotify",
						method: function (userInfo) {
							$.clientCallBacks["onUserOnlineNotify"](userInfo);
						}
					},
					{
						name: "onUserOfflineNotify",
						method: function (userId) {
							$.clientCallBacks["onUserOfflineNotify"](userId);
						}
					}
				]
			});
			//socket连接
			function signalrConnect() {
				$.signalrApi.start(function () {
					var userInfo = FLD.getUserInfo();
					$.signalrApi.server.serviceClientConnect(userInfo.UserId);
				});
			}
			signalrConnect();

			setInterval(function () {

				try {
					$.signalrApi.server.clientLive();
				} catch (e) {
					$.signalrApi.start(function () {
						var userInfo = FLD.getUserInfo();
						$.signalrApi.server.serviceClientConnect(userInfo.UserId);
					});
				}

			}, 2000);
		}

		api.addEventListener({
			name: 'refreshAboutUser'
		}, function (ret, err) {
			if (FLD.getUserInfo()) {
				vm.initChat();
			}

		});



		vm = new Vue({
			el: '#app',
			data: {
				showLoading: false,
				shoppingMallServerIP: 'http://' + FLD.shoppingMallServerIP,
				tabbarActive: 0,
				dot: 0,
				typeList: []
			},
			created: function () {
				var that = this;
				// return
				if (api.safeArea.bottom) {
					setTimeout(function () {
						$('.van-tabbar').css({
							'padding-bottom': api.safeArea.bottom + 'px'
						})

					}, 300)

				}

				that.openIndex();
				

				that.getTypes();

				that.checkNewAPP();

				// that.openAgreement()

				


				if (FLD.getUserInfo()) {
					that.initChat();
				}

			},
			methods: {
				checkNewAPP() {
					var that = this;
					var mam = api.require('mam');
					mam.checkUpdate(function (ret, err) {
						if (ret) {
							if (ret.result.update) {
								api.openFrame({
									name: 'updateAPP',
									url: 'common/updateAPP.html',
									bgColor: 'rgba(255,255,255,0)',
									rect: {
										x: 0,
										y: 0,
										w: api.winWidth,
										h: api.winHeight
									},
									pageParam:{
										updateData:ret.result
									}
								});
							}
						}
						that.openAgreement();
						that.openYD();
					});
				},
				initChat() {
					var that = this;
					FLD.ajax('sp_getSericeList', {}, function (res) {
						var userInfo = FLD.getUserInfo();
						mine = {
							username: userInfo.UserName,
							id: '',
							status: "online",
							sign: '',
							avatar: that.shoppingMallServerIP + userInfo.Picture
						}

						groups = [];
						friend = [];
						//用户列表
						for (var i = 0; i < res.ds.length; i++) {
							friend.push({
								username: res.ds[i].UserName,
								id: res.ds[i].UserID.toString(),
								status: res.ds[i].ContextIDs ? "online" : 'offline',
								sign: res.ds[i].Sign,
								avatar: res.ds[i].HeadImg,
								contextIDs: res.ds[i].ContextIDs
							})
						}
						//群列表
						// for (var i = 0; i < res.ds2.length; i++) {
						// 	groups.push({
						// 		groupname: res.ds2[i].GroupName,
						// 		id: res.ds2[i].GroupID.toString(),
						// 		avatar: "../../image/ql.png" //群组头像
						// 	})
						// }


						$.clientCallBacks["onServiceClientConnect"] = (data) => {
							var data_j = JSON.parse(data)
							mine["contextIDs"] = data_j.ContextID;
							mine["id"] = data_j.ChatUserId;
						}
						$.clientCallBacks["onChatMsg"] = (userId, msg, timestamp) => {
							let fs = friend.filter(item => item.id == userId);
							if (fs.length > 0) {
								var msgObj = {
									groupname: '',
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: fs[0].id,
									type: "friend", //聊天窗口来源类型，从发送消息传递的to里面获取
									content: msg,
									cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								}
								api.sendEvent({
									name: 'getChatMsg',
									extra: {
										msgObj: msgObj
									}
								});
								if (isOpenChatList) {
									api.sendEvent({
										name: 'checkChatList',
										extra: {
											msgObjArray: [msgObj]
										}
									});

								} else {
									that.setChatStorage([msgObj]);
									if (msg) {
										that.dot++;
									}

								}


								if (msg) {

									audioStreamer.onNormal();
									audioStreamer.openPlayer({
										path: 'widget://image/chat/msg.mp3',
									}, function (ret) {

									});
								}

							}
						}
						$.clientCallBacks["onGroupMsg"] = (userId, groupId, msg, timestamp) => {

							var getGroupList = function () {
								FLD.ajax('getGroupList', {}, function (res) {
									groups = [];
									for (var i = 0; i < res.ds.length; i++) {
										groups.push({
											groupname: res.ds[i].GroupName,
											id: res.ds[i].GroupID.toString(),
											avatar: "../../image/ql.png" //群组头像
										})
									}
									onGroupMsgGet();
								})
							}

							var onGroupMsgGet = function () {
								var fs = friend.filter(item => item.id == userId);

								var gs = groups.filter(item => item.id == groupId);
								if (gs.length == 0) {
									getGroupList();
								}
								if (fs.length > 0) {
									//接收消息
									var msgObj = {
										groupname: gs[0].groupname,
										username: fs[0].username,
										avatar: fs[0].avatar,
										id: groupId,
										type: "group", //聊天窗口来源类型，从发送消息传递的to里面获取
										content: msg,
										cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
										mine: false,  //是否我发送的消息，如果为true，则会显示在右方
										fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
										timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
									};


									api.sendEvent({
										name: 'getChatMsg',
										extra: {
											msgObj: msgObj
										}
									});

									if (isOpenChatList) {
										api.sendEvent({
											name: 'checkChatList',
											extra: {
												msgObjArray: [msgObj]
											}
										});
									} else {
										that.setChatStorage([msgObj]);
										if (msg) {
											that.dot++;
										}
									}


								}
							}

							onGroupMsgGet();
							if (msg) {
								audioStreamer.onNormal();
								audioStreamer.openPlayer({
									path: 'widget://image/chat/msg.mp3',
								}, function (ret) {

								});
							}



						}


						$.clientCallBacks["onUserOnlineNotify"] = (info) => {

						}

						$.clientCallBacks["onUserOfflineNotify"] = (userId) => {

						}

						signalRHelper();
						//获取未读信息
						setTimeout(function () {
							that.getUnReadMsg();
						}, 2000);
					})
				},
				setChatStorage(msgObjArray) {
					return false;
					var that = this;
					var sql = "select * from Chat where UserID='" + FLD.getUserInfo().UserID + "'";
					var chatPersonList_sql = DB.selectSqlSync(sql);
					if (chatPersonList_sql.length) {
						var chatPersonList = JSON.parse(chatPersonList_sql[0].JSONStr1);
						for (var i in msgObjArray) {
							if (msgObjArray[i].content) {
								if (msgObjArray[i].type == 'group') {
									msgObjArray[i].avatar = '../../image/ql.png';
								}
								var x = 0;
								for (var j in chatPersonList) {
									if (parseInt(chatPersonList[j].id) == parseInt(msgObjArray[i].id) && chatPersonList[j].type == msgObjArray[i].type) {
										x = 1;
										msgObjArray[i].unReadNum = (parseInt(chatPersonList[j].unReadNum) || 0) + 1;
										chatPersonList[j] = msgObjArray[i];
									}
								}
								if (x == 0) {
									msgObjArray[i].unReadNum = 1;
									chatPersonList.unshift(msgObjArray[i]);
								}
							}

						}

						var sql = "update Chat set JSONStr1='" + JSON.stringify(chatPersonList).replace(/\'/g, '\'\'') + "',UpdateTime='" + FLD.getFormatDate() + "' where ChatID='" + chatPersonList_sql[0].ChatID + "'";
						DB.executeSql(sql, function () {

						})

					} else {
						var sql = "insert into Chat (UserID,JSONStr1,CreateTime) values ('" + FLD.getUserInfo().UserID + "','" + JSON.stringify(msgObjArray).replace(/\'/g, '\'\'') + "','" + FLD.getFormatDate() + "')"
						DB.executeSql(sql, function () {

						})
					}
				},
				getUnReadMsg() {
					var that = this;
					FLD.ajax('getUnReadMsg', {}, function (res) {
						var unReadMsgObj = [];
						for (var i = 0; i < res.ds.length; i++) {
							//每条消息重新发送给当前用户
							var fs = friend.filter(function (item) {
								return item.id == res.ds[i].FromUserID;
							})
							if (fs.length > 0) {
								//接收消息
								var msgObj = {
									groupname: '',
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: fs[0].id,
									type: "friend",  //聊天窗口来源类型，从发送消息传递的to里面获取
									content: res.ds[i].Content,
									cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: res.ds[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								};

								unReadMsgObj.push(msgObj)

							}
						}
						for (var i = 0; i < res.ds1.length; i++) {
							var fs = friend.filter(function (item) {
								return item.id == res.ds1[i].FromUserID;
							})
							var gs = groups.filter(function (item) {
								return item.id == res.ds1[i].GroupID;
							});
							if (fs.length > 0) {
								//接收消息
								var msgObj = {
									groupname: gs[0].groupname,
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: res.ds1[i].GroupID,
									type: "group",  //聊天窗口来源类型，从发送消息传递的to里面获取
									content: res.ds1[i].Content,
									cid: 0, //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: res.ds1[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								};

								unReadMsgObj.push(msgObj)

							}
						}

						if (isOpenChatList) {
							api.sendEvent({
								name: 'checkChatList',
								extra: {
									msgObjArray: unReadMsgObj
								}
							});
						} else {
							if (unReadMsgObj.length) {
								that.dot = unReadMsgObj.length;
								audioStreamer.onNormal();
								audioStreamer.openPlayer({
									path: 'widget://image/chat/msg.mp3',
								}, function (ret) {

								});
							}
						}

					})
				},
				openAgreement() {
					if (!window.localStorage.getItem('ifAggreAgreement')) {
						api.openFrame({
							name: 'agreement',
							url: 'common/agreement.html',
							bgColor: 'rgba(255,255,255,0)',
							rect: {
								x: 0,
								y: 0,
								w: api.winWidth,
								h: api.winHeight
							}
						});
					}
				},
				openYD() {
					if (!window.localStorage.getItem('ifGuide')) {
						api.openFrame({
							name: 'guide',
							url: 'common/guide.html',
							bgColor: 'rgba(255,255,255,0)',
							rect: {
								x: 0,
								y: 0,
								w: api.winWidth,
								h: api.winHeight
							}
						});
					}
				},
				openIndex() {
					api.openFrame({
						name: 'index',
						url: './index.html',
						rect: {
							x: 0,
							y: 0,
							w: api.winWidth,
							h: api.winHeight - 50 - api.safeArea.bottom
						}
					});
				},
				openChat() {
					var that = this;
					FLD.mustLogin(function () {
						var row = {
							id: friend[0].id,
							groupname: '',
							username: friend[0].username,
							avatar: friend[0].avatar,
							type: 'friend',
							timestamp: moment().valueOf()
						}
						api.openWin({
							name: 'chatListDetail',
							url: 'chat/chatListDetail.html',
							reload: true,
							slidBackEnabled: false,
							pageParam: {
								row: row,
								id: mine.id
							}
						})
					})
				},
				getTypes() {
					var that = this;
					FLD.ajax('sp_allProductType', {}, function (res) {
						that.typeList = res.ds;
					})
				},
				changeTabbar(index) {
					var that = this;
					var url = '';
					if (index == 0) {
						url = 'index';
					} else if (index == 1) {
						url = 'vin';
					} else if (index == 2) {
						url = 'chat/chatListDetail';
					} else if (index == 3) {
						url = 'shoppingCart';
					} else if (index == 4) {
						url = 'userMenu';
						api.sendEvent({
							name: 'refreshAboutUser'
						});
					}

					if (index == 3) {
						that.tabbarActive = -1;
						FLD.mustLogin(function () {
							api.openWin({
								name: url,
								url: url + '.html',
								reload: true,
								slidBackEnabled: false
								
							})
						})

					} else if (index == 2) {

						var detailTypeList = [];
						// for (var i in that.typeList) {
						// 	if (that.typeList[i].ParentCategoryId == 0) {
						// 		for (var j in that.typeList) {
						// 			if (that.typeList[i].CategoryId == that.typeList[j].ParentCategoryId) {
						// 				detailTypeList.push(that.typeList[j])
						// 			}
						// 		}
						// 	}

						// }

						// for (var i in detailTypeList) {
						// 	var node = [];
						// 	for (var j in that.typeList) {
						// 		if (detailTypeList[i].CategoryId == that.typeList[j].ParentCategoryId) {
						// 			node.push(that.typeList[j])
						// 		}
						// 	}
						// 	detailTypeList[i].typeNode = node;
						// }



						var repeatNode = function(id){
							var node = []
							for(var i in that.typeList){
								if(id == that.typeList[i].ParentCategoryId){
									var newNode = that.typeList[i];
									newNode.typeNode = repeatNode(that.typeList[i].CategoryId);
									node.push(newNode);
								}
							}
							return node;
						}
						detailTypeList = repeatNode(0);

						



						api.openFrame({
							name: 'channel',
							url: 'channel.html',
							rect: {
								x: 0,
								y: 0,
								w: api.winWidth,
								h: api.winHeight - 50 - api.safeArea.bottom
							},
							
							pageParam: {
								detailTypeList: detailTypeList,
								form: 'base'
							}
						});

					} else {
						api.openFrame({
							name: url,
							url: './' + url + '.html',
							allowEdit:url == 'vin'?true:false,
							rect: {
								x: 0,
								y: 0,
								w: api.winWidth,
								h: api.winHeight - 50 - api.safeArea.bottom
							}
						});
					}


				}

			}
		})
	};
</script>

</html>